package org.tln.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.tln.db137.common.JwtUtils;
import org.tln.db137.common.R;
import org.tln.db137.entity.Menu;
import org.tln.db137.entity.User;
import org.tln.db137.service.UserService;

import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin("*")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 人教版
     */
    @PostMapping("/loginTwo")
    public R login2(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();//构建一个查询容器
        queryWrapper.setEntity(user);
        User one = this.userService.getOne(queryWrapper);
        if(one!=null) {//登陆成功
            //生产token
            //JWT
            HashMap<String,Object> map = new HashMap<>();
            map.put("userid",one.getId());
            String string = JwtUtils.createJwtToken(map);
            System.out.println("string = " + string);
            return new R().add("token",string);
        }else {//登陆失败
            return new R().setCode(404).setMessage("登陆出错");
        }
    }
    /**
     * 根据登陆用户返回用户菜单集合数据
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("uname",user.getUname());
        wrapper.eq("upwd",user.getUpwd());
        return userService.list(wrapper);
    }

    @GetMapping("/selectmenu")
    public Object selectmenu(@RequestHeader("token") String mytoken) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        System.out.println("mytoken = " + mytoken);
        Integer id=JwtUtils.getJwtToken(mytoken,"userid");
        queryWrapper.eq("id",id);
        List<User> userList = this.userService.list(queryWrapper);
        List< Menu> menuList=this.userService.selectUserMenuByUserID(id);
        return  new R().add("menuList",menuList).add("user",userList.get(0));
    }

    @PostMapping("/updateUser")
    public Object updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }
    @PostMapping("/register")
    public Object register(@RequestBody User user) {
        return userService.save(user);
    }
    /**
     * 查询所有用户
     */
    @GetMapping("/userlist")
    public R userlist() {
        List<User> userList = this.userService.list();
        return new R().add("userList",userList);
    }
    @PostMapping("/deleteuser")
    public Object deleteUser(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",user.getId());
        return userService.remove(wrapper);
    }
}
